/*
 * CheckMsgQue.c
 *
 *  Created on: Nov 4, 2012
 *      Author: lakshmanas
 */


#include<stdio.h>
#include<unistd.h>
#include "mq_interface.h"


void
mq_send_prog_1(char *host)
{
        CLIENT *clnt;
        Msg_t  *result_1;
        nametype  source="student";
        int  *result_2;



#ifndef DEBUG
        clnt = clnt_create (host, MQ_SEND_PROG, MQ_PROG_VERS, "udp");
        if (clnt == NULL) {
                clnt_pcreateerror (host);
                exit (1);
        }
#endif  /* DEBUG */

        //check messages for advisor, by student (message whose source is student),
        result_1 = checkmsg_1(&source, clnt);
        if (result_1 == (Msg_t *) NULL) {
        	//clnt_perror (clnt, "call failed");
        	printf("No messages from Student \n");
        }
        else
        {
        	printf("Message for advisor from student");
            printf("\nSource : %s  \n "
            		"Student ID: %d  Name :%s \n"
            		"Course Id : %d  Name :%s \n"
            		"clearance : %d \n",
            (*result_1)->source,(*result_1)->student_id,(*result_1)->student_name,(*result_1)->course_id,(*result_1)->course_name,(*result_1)->clearance);

            //approve the message and change source and clearance flag
            //printf("Advisor approved %s to take %s course \n",(*result_1)->student_name,(*result_1)->course_name);
			(*result_1)->source="advisor";
			long rand = random();
			printf("%d",rand);
			if(rand%2==0){
				(*result_1)->clearance=0;
				printf("Advisor approved %s to take %s course \n",(*result_1)->student_name,(*result_1)->course_name);
			}
			else{
				printf("Advisor didn't approve %s to take %s course \n",(*result_1)->student_name,(*result_1)->course_name);
			}

			// send the approved message to the notification process to inform the student with source as advisor
			result_2 = sendmsg_1(result_1, clnt);
			if (result_2 == (int *) NULL) {
				clnt_perror (clnt, "call failed");
				printf("Advisor message Sent unsuccessful for Student notification\n");
			}else
				printf("Advisor Message Sent successful for Student notification \n");
        }

#ifndef DEBUG
        clnt_destroy (clnt);
#endif   /* DEBUG */
}


int
main (int argc, char *argv[])
{
        char *host;
        host = "localhost";
        while(1){
        mq_send_prog_1 (host);
        sleep(3);
        }
        exit (0);
}
